package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.UserSearchDto;
import com.heima.search.service.ApAssociateWordsService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class ApAssociateWordsServiceImpl implements ApAssociateWordsService {

    @Autowired
    private RestHighLevelClient client;
    /**
     * 自动补全功能，关键字联想功能，使用es
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) {
        //1.还是搜索
        try {
            SearchRequest searchequest=new SearchRequest("app_info_article");

            //执行自动补全
            searchequest.source().suggest(new SuggestBuilder().
                    addSuggestion("mySuggestion",//指定自动补全的名称，方便后期数据解析
                            SuggestBuilders.completionSuggestion("suggestion")//指定自动补全实施的字段名称
                            .prefix(dto.getSearchWords())//根据关键字作为前缀，
                            .skipDuplicates(true)//如果查询的有重复的则跳过
                            .size(dto.getPageSize())//最多展示10条
                    ));

            SearchResponse searchResponse = client.search(searchequest, RequestOptions.DEFAULT);
            //2.解析数据结果

            Suggest suggest = searchResponse.getSuggest();
            CompletionSuggestion mySuggestion = suggest.getSuggestion("mySuggestion");
            List<CompletionSuggestion.Entry.Option> options = mySuggestion.getOptions();

            List<String> list=new ArrayList<>(options.size());

            for (CompletionSuggestion.Entry.Option option : options) {
                Text text = option.getText();
                list.add(text.toString());
            }
            return ResponseResult.okResult(list);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseResult.okResult("出现异常了");
        }
    }
}
